﻿namespace LiteBlog.Repositories
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;
    using LiteBlog.Common.Entities;
    using LiteBlog.Repositories.Contracts;
    using LiteBlog.Common.Enums;
    using LiteBlog.Repositories.Framework;
    using LiteBlog.Repositories.Common;

    public class TagRepository : StandardRepository<Tag>, ITagRepository
    {

        public TagRepository(IDataContext context, IXmlHelper xmlHelper) : base(context, xmlHelper)
        {
            _path = context.GetPath(DataStoreType.Tags, null);
            _elementName = Elem.Tag;
            _idName = Attr.Id3;
        }

        internal IList<Tag> GetTags(string csvIds)
        {
            var filteredTags = new List<Tag>();
            var tagIds = csvIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (tagIds.Length > 0)
            {
                var tags = Get();
                filteredTags = tags.Where(t => tagIds.Any(tagId => tagId.Trim().Equals(t.TagId)))
                                   .ToList();
            }
            return filteredTags;
        }

        protected override Tag GetEntity(XElement elem)
        {
            var tag = new Tag();
            tag.TagId = elem.Attribute(Attr.Id3).Value;
            tag.Name = elem.Attribute(Attr.Name).Value;
            tag.Count = (int)elem.Attribute(Attr.Count);
            return tag;
        }

        protected override XElement GetElement(Tag item)
        {
            return new XElement(
                Elem.Tag,
                new XAttribute(Attr.Id3, item.TagId),
                new XAttribute(Attr.Name, item.Name),
                new XAttribute(Attr.Count, item.Count)
                );
        }

        protected override void UpdateElement(XElement elem, Tag item)
        {
            elem.SetAttributeValue(Attr.Id3, item.TagId);
            elem.SetAttributeValue(Attr.Name, item.Name);
        }

        protected override string GetId(Tag item)
        {
            return item.TagId;
        }

        protected override void SetId(Tag tag, string id)
        {
            tag.TagId = id;
        }
    }
}